package com.yu.blog.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;


public class CaptchaUtils {


    private int width = 160;
    private int height = 40;
    private int lineCount = 20;
    private String code;
    private BufferedImage buffImg = null;

    Random random = new Random();


    public void CreateImageCode(int width, int height, String code, int lineCount) {
        this.width = width;
        this.height = height;
        this.code = code;
        this.lineCount = lineCount;
        this.creatImage();
    }

    /**
     * 绘制验证码
     */
    private void creatImage() {
        int fontWidth = width / code.length();
        int fontHeight = height - 5;
        int codeY = height - 8;
        this.buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        Graphics graphics = buffImg.getGraphics();
        graphics.setColor(getColor(200,250));
        graphics.fillRect(0, 0, width, height);
        //绘制验证码，字体加粗
        graphics.setFont(new Font("Arial", Font.BOLD, fontHeight));
        //绘制line条干扰线
        for (int i = 0; i < lineCount; ++i) {
            int xBegin = random.nextInt(width);
            int yBegin = random.nextInt(height);
            int xEnd = xBegin + random.nextInt(width);
            int yEnd = yBegin + random.nextInt(height);
            graphics.setColor(getColor(1,200));
            //绘制线条
            graphics.drawLine(xBegin, yBegin, xEnd, yEnd);
        }
        int area = (int) (0.01F * width * height);
        for (int i = 0; i < area; ++i) {
            int xBegin = random.nextInt(width);
            int yBegin = random.nextInt(height);
            buffImg.setRGB(xBegin, yBegin, random.nextInt(255));
        }
        for (int i = 0; i < code.length(); ++i) {
            String str = code.substring(i, i + 1);
            graphics.setColor(getColor(1,200));
            graphics.drawString(str, i * fontWidth + 3, codeY);
        }

    }

    /**
     * 随机生成颜色
     */
    public Color getColor(int numA, int numB) {
        if (numA > 255) {
            numA = 255;
        }
        if (numB > 255) {
            numB = 255;
        }
        int r = numA + random.nextInt(numB - numA);
        int g = numA + random.nextInt(numB - numA);
        int b = numA + random.nextInt(numB - numA);
        return new Color(r, g, b);
    }

    /**
     * 输出图片
     */
    public void write(OutputStream output) throws IOException {
        ImageIO.write(buffImg, "png", output);
        output.close();
    }
}









